#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created by master on 2017/3/5
import socket

ip_port = ("127.0.0.1", 9999)

sk = socket.socket()
sk.connect(ip_port)

while True:
    user_input = input(">>:").strip()  # 接收用户输入
    if len(user_input) == 0: continue
    if user_input == "q": break

    sk.send(bytes(user_input, "utf8"))  # 转码，发送
    server_ack_msg = sk.recv(100)  # 接收文件信息
    cmd_res_msg = str(server_ack_msg.decode()).split("|")
    cmd_res_size = 0
    if cmd_res_msg[0] == "CMD_RESULT_SIZE":  # 如果文件信息接收成功
        cmd_res_size = int(cmd_res_msg[1])  # 获取要接收的文件的长度
        sk.send(bytes("CLIENT_READY_TO_RECV", "utf8"))  # 告诉服务器 客户端准备接收数据
    res = ""
    received_size = 0
    while received_size < cmd_res_size:  # 如果已收到的文件长度小于文件的总长度 继续接收
        data = sk.recv(1024)  # 每次接收1024字节
        received_size += len(data)  # 累加收到的文件长度
        res += str(data.decode())  # 累加文件内容
    else:
        print(res)
        print("---------received  done-----")

sk.close()
